<template>
  <t-card :bordered="false">
    <!-- 容器 -->
    <div class="container">
      <t-space class="left" direction="vertical">
        <!-- 公司 -->
        <!-- <t-select 
          v-model:value="searchParams.companyId" 
          :options="companySimpleList"
          :keys="{ label: 'name', value: 'id' }" 
          label="归属公司：" 
          filterable 
          @change="handleChangeCompany" /> -->
        <!-- 新建模板 -->
        <t-button 
          v-permission="['system:engineering-stage-model:create']" 
          block 
          @click="
          handleOpenLeftDialog('create', {
            
          })
          ">
          新建模板
        </t-button>
        <!-- 模板树 -->
        <t-tree 
          :data="categoryTree" 
          activable 
          expand-on-click-node 
          hover 
          :keys="{ label: 'name', value: 'id' }"
          max-height="calc(100vh - 380px)" 
          @click="handleClickCategoryTree"
        >
          <template #operations="{ node }">
            <t-space>
              <t-icon v-permission="['system:engineering-stage-model:update']" name="edit"
                @click="handleOpenLeftDialog('update', { id: node.data.id })" />
              <t-popconfirm content="确认要删除该项吗？" @confirm="handleDeleteLeft({ id: node.data.id })">
                <t-icon v-permission="['system:engineering-stage-model:delete']" name="delete" />
              </t-popconfirm>
            </t-space>
          </template>
        </t-tree>
      </t-space>
      <t-divider class="divider" layout="vertical" />
      <div v-show="searchParams.modelId" class="right">
        <!-- 自定义搜索 -->
        <custom-search ref="customSearchRef" v-slot="{ params }" @submit="handleInitTable">
          <t-col :span="4">
            <t-form-item label="节点名称" name="stageName">
              <t-input v-model:value="params.stageName" clearable placeholder="" />
            </t-form-item>
          </t-col>
          <t-col :span="4">
            <t-form-item label="发送通知" name="sendStatus">
              <t-select
              v-model:value="params.sendStatus"
              :options="dictionaryStore.get('is_type')"
              clearable
              filterable
              placeholder=""
            />
            </t-form-item>
          </t-col>
          <t-col :span="4">
            <t-form-item label="创建时间" name="createTime">
              <t-date-range-picker
                allow-input 
                v-model:value="params.createTime" 
                clearable 
                enable-time-picker 
                placeholder=" "
                style="width: 100%" />
            </t-form-item>
          </t-col>
        </custom-search>
        <!-- 自定义表格 -->
        <custom-table 
          ref="customTableRef" 
          row-key="id" 
          :columns="columns" 
          :api="engineeringConfigCRUD.page"
          column-controller-key="engineeringConfig" 
          :on-before-set-data="handleTableSetData"
          :tree="{ expandTreeNodeOnClick: true }" 
          fixed-page-size>
          <template #topContent>
            <div style="margin-bottom: var(--td-comp-margin-xxl)">
              <t-button v-permission="['system:engineering-stage-config:create']" @click="handleOpenDialog('create', {
                messageModelIds: [],
                wsgMessageIds: [],
                wkgMessageIds: [],
                wwgMessageIds: [],
                parentId: 0,
               
                modelId: searchParams.modelId,
                level: 1
              })">
                新建节点
              </t-button>
            </div>
          </template>
          <template #sort="{ row }">
            {{ (row.sort).toFixed(2) }}
          </template>
          <template #engineeringNode="{ row }">
            {{ dictionaryStore.analysis('engineering_team_groups', row.engineeringNode) }}
          </template>
          <template #sendStatus="{ row }">
            {{ dictionaryStore.analysis('is_type', row.sendStatus) }}
          </template>
          <template #uploadStatus="{ row }">
            {{ dictionaryStore.analysis('is_type', row.uploadStatus) }}
          </template>
          <template #notificationType="{ row }">
            {{ dictionaryStore.analysis('system_notice_type', row.notificationType) }}
          </template>
          <template #isParallel="{ row }">
            {{ dictionaryStore.analysis('is_type', row.isParallel) }}
          </template>
          <template #operation="{ row }">
            <t-space break-line>
              <t-link theme="primary" v-permission="['system:engineering-stage-config:create']" @click.stop="handleOpenDialog('create', {
                parentId: row.id,
                messageModelIds: [],
                wsgMessageIds: [],
                wkgMessageIds: [],
                wwgMessageIds: [],
                level: row.level + 1,
              
                modelId: searchParams.modelId,
              })">
                新建子级
              </t-link>
              <t-link theme="primary" v-permission="['system:engineering-stage-config:query']"
                @click.stop="handleOpenDialog('read', { id: row.id })">
                详情
              </t-link>
              <t-link theme="primary" v-permission="['system:engineering-stage-config:update']"
                @click.stop="handleOpenDialog('update', { id: row.id })">
                编辑
              </t-link>
              <t-popconfirm content="确认要删除该项吗？" @confirm="handleDelete({ id: row.id })">
                <t-link v-permission="['system:engineering-stage-config:delete']" theme="danger"> 删除 </t-link>
              </t-popconfirm>
            </t-space>
          </template>
        </custom-table>
      </div>
      <t-empty v-show="!searchParams.modelId" class="right" title="请先选择模板" style="margin-top: 30vh" />
    </div>
    <!-- 自定义对话框 -->
    <custom-dialog ref="customDialogRef" v-slot="{ formData, readonly, mode }" :api-map="engineeringConfigCRUD"
      header="*节点" :label-width="120" :on-before-set-data="handleDialogSetData"
      :on-before-save-data="handleDialogSaveData" @request-success="handleDialogRequestSuccess">
      <t-form-item v-if="mode !== 'create'" label="上级节点" name="parentId"
        :rules="[{ required: true, message: '请选择上级节点' }]">
        <t-cascader v-model:value="formData.parentId" :options="simpleMenuList"
          :keys="{ value: 'id', label: 'stageName' }" placeholder="请选择上级节点" filterable clearable :readonly="readonly"
          check-strictly />
      </t-form-item>
      <t-form-item label="节点名称" name="stageName" :rules="[{ required: true, message: '请输入节点名称' }]">
        <t-input v-model:value="formData.stageName" placeholder="请输入节点名称" clearable :readonly="readonly" />
      </t-form-item>
      <t-form-item label="显示顺序" name="sort" :rules="[{ required: true, message: '请输入显示顺序' }]">
        <t-input-number v-model:value="formData.sort" placeholder="请输入显示顺序" :decimal-places="2" clearable
          :readonly="readonly" style="width: 100%" />
      </t-form-item>
      <t-form-item label="施工节点" name="engineeringNode" :rules="[{ required: true, message: '请选择施工节点' }]">
        <t-select v-model:value="formData.engineeringNode" :options="dictionaryStore.get('engineering_team_groups')"
          clearable filterable placeholder="" :readonly="readonly" />
      </t-form-item>
      <t-form-item label="发送通知" name="sendStatus" :rules="[{ required: true, message: '请选择发送通知' }]">
        <t-radio-group v-model:value="formData.sendStatus">
          <t-radio v-for="_ in dictionaryStore.get('is_type')" :key="_.value" :value="_.value" :readonly="readonly">
            {{ _.label }}
          </t-radio>
        </t-radio-group>
      </t-form-item>
      <t-form-item v-if="formData.sendStatus == '1'" :label="formData.level === 1 ? '施工班组通知' : '消息模板'" name="messageModelIds"
        :rules="[{ required: true, message: '请选择' }]">
        <!-- 选择消息模板 -->
        <message-template-selector v-model:selectedMessageIds="formData.messageModelIds" :readonly="readonly"
          multiple />
      </t-form-item>
      <t-form-item v-if="formData.sendStatus == '1' && [1].includes(formData.level)" label="阶段未开工消息" name="wkgMessageIds"
        :rules="[{ required: true, message: '请选择阶段未开工消息' }]">
        <!-- 选择阶段未开工消息 -->
        <message-template-selector v-model:selectedMessageIds="formData.wkgMessageIds" :readonly="readonly" multiple />
      </t-form-item>
      <t-form-item v-if="formData.sendStatus == '1' && [1].includes(formData.level)" label="阶段未完工消息" name="wwgMessageIds"
        :rules="[{ required: true, message: '请选择阶段未完工消息' }]">
        <!-- 选择未完工消息 -->
        <message-template-selector v-model:selectedMessageIds="formData.wwgMessageIds" :readonly="readonly" multiple />
      </t-form-item>
      <t-form-item v-if="formData.sendStatus == '1' && [1].includes(formData.level)" label="阶段未施工消息" name="wsgMessageIds"
        :rules="[{ required: true, message: '请选择阶段未施工消息' }]">
        <!-- 选择阶段未施工消息 -->
        <message-template-selector v-model:selectedMessageIds="formData.wsgMessageIds" :readonly="readonly" multiple />

      </t-form-item>
      <t-form-item label="上传文件" name="uploadStatus" :rules="[{ required: true, message: '请选择上传文件' }]">
        <t-radio-group v-model:value="formData.uploadStatus">
          <t-radio v-for="_ in dictionaryStore.get('is_type')" :key="_.value" :value="_.value" :readonly="readonly">
            {{ _.label }}
          </t-radio>
        </t-radio-group>
      </t-form-item>
      <t-form-item label="上节点并行" name="isParallel" :rules="[{ required: true, message: '请选择上节点并行' }]">
        <t-radio-group v-model:value="formData.isParallel">
          <t-radio v-for="_ in dictionaryStore.get('is_type')" :key="_.value" :value="_.value" :readonly="readonly">
            {{ _.label }}
          </t-radio>
        </t-radio-group>
      </t-form-item>
      <t-form-item label="最小施工天数" name="minTime" :rules="[{ required: true, message: '请输入最小施工天数' }]" v-if="[1].includes(formData.level)">
        <t-input v-model:value="formData.minTime" placeholder="请输入最小施工天数" clearable :readonly="readonly" />
      </t-form-item>

    </custom-dialog>

    <!-- 左侧新增材料对话框 -->
    <custom-dialog ref="customDialogLeftRef" v-slot="{ formData, readonly }" :api-map="engineeringModelCRUD"
      header="*节点" @request-success="handleDialogRequestSuccessLeft">
      <t-form-item label="模板名称" name="name" :rules="[{ required: true, message: '请输入模板名称' }]">
        <t-input v-model:value="formData.name" placeholder="请输入模板名称" clearable :readonly="readonly" />
      </t-form-item>
    </custom-dialog>
  </t-card>
</template>


<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin, TableCol, TreeNodeModel } from 'tdesign-vue-next';
import { onMounted, reactive, ref, useTemplateRef, watch } from 'vue';

import { engineeringConfigCRUD, engineeringModelCRUD } from '@/api/config/common-config';
import { messageTemplateCRUD } from '@/api/config/message-template';
import { getSimpleRoleList } from '@/api/system/role';
import { getSimpleUserList } from '@/api/system/user';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/tree-table/index.vue';
import MessageTemplateSelector from '@/components/message-template-selector/index.vue'
import { useDictionaryStore } from '@/store';
import listToTree from '@/utils/listToTree';
import { getCompanyList } from '@/api/system/dept';

// 字典仓库
const dictionaryStore = useDictionaryStore();
// 搜索参数
const searchParams = reactive({
 
  modelId: null
});
// 公司精简列表
const companySimpleList = ref([]);
// 处理获取公司精简列表
const handleGetCompanySimpleList = async () => {
  return getCompanyList().then((data) => {
    companySimpleList.value = data;
    
  });
};
// 模板列表
const categoryList = ref([]);
// 模板树
const categoryTree = ref([]);
// 处理获取模板
const handleGetCategory = () => {
  const params = {
    
    pageSize: -1,
  };
  engineeringModelCRUD.page(params).then((data) => {
    categoryList.value = data.list;
    categoryTree.value = listToTree(data.list);
  });
};
// 自定义搜索ref
const customSearchRef = useTemplateRef('customSearchRef');
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// columns
const columns: TableCol[] = [
  { colKey: 'stageName', title: '节点名称' },
  { colKey: 'level', title: '节点层级' },
  { colKey: 'sort', title: '显示顺序' },
  { colKey: 'engineeringNode', title: '施工节点' },
  { colKey: 'sendStatus', title: '发送通知' },
  { colKey: 'uploadStatus', title: '上传文件' },
  { colKey: 'isParallel', title: '上节点并行' },
  // { colKey: 'wwgMessageIds', title: '未完工消息' },
  // { colKey: 'wkgMessageIds', title: '阶段未开工消息' },
  // { colKey: 'wsgMessageIds', title: '阶段未施工消息' },
  { colKey: 'operation', title: '操作', width: 250 },
];
// 处理点击模板树
const handleClickCategoryTree = ({ node }: { node: TreeNodeModel }) => {
  if (!node.data.children) {
    searchParams.modelId = node.value;
    handleInitTable();
  }
};
// 自定义材料左侧对话框ref
const customDialogLeftRef = useTemplateRef('customDialogLeftRef');
// 处理打开对话框
const handleOpenLeftDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  customDialogLeftRef.value.open(mode, params);
};
// 处理对话框请求成功
const handleDialogRequestSuccessLeft = (result: Record<string, any>) => {
  handleGetCategory();
};
// 处理删除左侧
const handleDeleteLeft = (params: Record<string, any>) => {
  if (params.children) {
    MessagePlugin.error('有子节点不允许删除');
  } else {
    engineeringModelCRUD
      .delete(params)
      .then(() => {
        MessagePlugin.success('删除成功');
        handleGetCategory();
        searchParams.modelId = null;
      })
      .catch(({ message }) => {
        MessagePlugin.error(message);
      });
  }

};
// 处理初始化表格
const handleInitTable = () => {
  const params = { ...customSearchRef.value.params, modelId: searchParams.modelId,  pageSize: -1 };
  customTableRef.value.initTable(params);
};
// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};
// 处理表格设置数据
const handleTableSetData = (data: any) => {
  return listToTree(data.list);
};
onMounted(async () => {
  // await handleGetCompanySimpleList();
  handleGetCategory();
});
// 精简菜单列表
const simpleMenuList = ref([]);
// 处理获取精简菜单列表
const handleGetSimpleMenuList = () => {
  simpleMenuList.value = [];
  const params = {
    pageSize: -1
  }
  engineeringConfigCRUD.page(params)
    .then((data) => {
      simpleMenuList.value = listToTree(data.list);
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  handleGetSimpleMenuList();
  customDialogRef.value.open(mode, params);
};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'create') handleInitTable();
  if (result.mode === 'update') handleRefreshTable();
};
// 处理删除
const handleDelete = (params: Record<string, any>) => {
  engineeringConfigCRUD
    .delete(params)
    .then(() => {
      MessagePlugin.success('删除成功');
      handleRefreshTable();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};

// 精简角色列表
const simpleRoleList = ref([]);
// 处理获取精简角色列表
const handleGetSimpleRoleList = () => {
  getSimpleRoleList().then((data) => {
    simpleRoleList.value = data;
  });
};
handleGetSimpleRoleList();
// 精简用户列表
const simpleUserList = ref([]);
// 处理获取精简用户列表
const handleGetSimpleUserList = () => {
  getSimpleUserList().then((data) => {
    simpleUserList.value = data;
  });
};
handleGetSimpleUserList();

// 处理对话框设置数据
const handleDialogSetData = (params: Record<string, any>) => {
  if (!params.wwgMessageIds) {
    params.wwgMessageIds = []
  } else {
    params.wwgMessageIds = messageModelList.value.filter(obj => params.wwgMessageIds.includes((obj.id).toString()))

  }
  if (!params.wkgMessageIds) {
    params.wkgMessageIds = []
  } else {
    params.wkgMessageIds = messageModelList.value.filter(obj => params.wkgMessageIds.includes((obj.id).toString()))

  }
  if (!params.wsgMessageIds) {
    params.wsgMessageIds = []
  } else {
    params.wsgMessageIds = messageModelList.value.filter(obj => params.wsgMessageIds.includes((obj.id).toString()))

  }
  if (!params.messageModelIds) {
    params.messageModelIds = []
  } else {
    params.messageModelIds = messageModelList.value.filter(obj => params.messageModelIds.includes((obj.id).toString()))
  }

};
// 全部消息模板
const messageModelList = ref([])
// 获取所有的消息配置模板
const handleGetMessageModelList = () => {
  const requestParams = {
    pageSize: -1
  }
  messageTemplateCRUD.page(requestParams).then((data) => {
    messageModelList.value = data.list

  })
}
handleGetMessageModelList()

// 处理对话框保存数据
const handleDialogSaveData = (params: Record<string, any>) => {
  params.messageModelIds = params.messageModelIds.map((item: any) => item.id)
  params.wwgMessageIds = params.wwgMessageIds.map((item: any) => item.id)
  params.wkgMessageIds = params.wkgMessageIds.map((item: any) => item.id)
  params.wsgMessageIds = params.wsgMessageIds.map((item: any) => item.id)
};
// 公司change
const handleChangeCompany = () => {
  searchParams.modelId = null;
  handleGetCategory();
}
</script>

<style lang="less" scoped>
:deep(.t-form__controls-content) {
  flex-wrap: wrap;
}

// 容器
.container {
  display: flex;
  justify-content: center;
  align-items: flex-start;

  .left {
    width: 280px;
    height: calc(100vh - 236px);
    overflow: hidden;

    :deep(.t-tree) {
      padding-right: 8px;

      &::-webkit-scrollbar {
        width: 8px;
        background: transparent;
      }

      &::-webkit-scrollbar-thumb {
        border-radius: 6px;
        border: 2px solid transparent;
        background-clip: content-box;
        background-color: var(--td-scrollbar-color);
      }
    }
  }

  .divider {
    height: calc(100vh - 236px);
  }

  .right {
    // width: calc(100% - 325px);
    flex: 1;
  }
}
</style>
